import {defineStore} from "pinia";
import {ref} from "vue";
// store/use-user-store.ts
import Cookies from 'js-cookie'
const remember = ref(false)
const cookiesStorage = {
    setItem (key, state) {
        console.log(`setItem ${key} -- ${state}`)
        //state不知道从哪里来的,竟然是json格式的数据,把他转化一下
        let stateToken = JSON.parse(state);
        //这里加判断语句,如果勾选选了记住密码就存放token

        if(remember.value){
            return Cookies.set(key, stateToken.token, { expires: 3 })
        }else {
            return Cookies.set(key, stateToken.token)
        }
    },
    getItem (key) {
        return JSON.stringify({
            token: Cookies.get(key),
        })
    },
}

export const useTokenStore = defineStore('token', {
    //存数据地方
    state() {
        return {
            token: '',
        };
    },
    // actions 里面放一个一个方法
    actions: {
        setToken(newToken,rem) {
            this.token = newToken;
            remember.value = rem;
        },
        removeToken() {
            this.token = '';
        },
    },
    persist: {
        enabled: true, // 开启缓存  默认会存储在本地localstorage
        storage: cookiesStorage
    }
});